<?php


namespace App\Resource\Controller;

use App\Common\Constants\ErrorCode;
use App\Common\Constants\Stakeholder;
use App\Common\Controller\AbstractController;
use App\Common\Middleware\JwtAuthMiddleware;
use App\Common\Middleware\PermissionMiddleware;
use App\Common\Service\BaseService;
use App\Order\Service\OrderService;
use App\Resource\Request\ShopRequest;
use App\Resource\Service\CategoryService;
use App\Resource\Service\CrdCartService;
use App\Resource\Service\ShareService;
use App\Resource\Service\ResourceService;
use App\Resource\Service\ShopService;
use App\Resource\Service\TeamLeaderService;
use App\Resource\Service\StoreShopMessageService;
use App\Resource\Service\StoreShopPrinterService;
use App\Resource\Service\StoreShopDeliverService;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;

/**
 * 相关店铺信息服务(小程序、商家端、web后台)
 * @Controller()
 * @Middlewares({
 *     @Middleware(JwtAuthMiddleware::class),
 *     @Middleware(PermissionMiddleware::class)
 * })
 * Class ShopController
 * @package App\Resource\Controller
 */
class ShopController extends AbstractController
{

    /**
     * @Inject()
     * @var ShopService
     */
    private $storeShopService;


    /**
     * @Inject()
     * @var ResourceService
     */
    private $resourceService;

    /**
     * @Inject()
     * @var TeamLeaderService
     */
    private $teamLeaderService;

    /**
     * @Inject()
     * @var CategoryService
     */
    private $categoryService;

    /**
     * @Inject()
     * @var CrdCartService
     */
    private $crdCartService;

    /**
     * @Inject()
     * @var ShareService
     */
    private $shareService;

    /**
     * @Inject()
     * @var OrderService
     */
    private $orderService;

    /**
     * @Inject()
     * @var BaseService
     */
    private $baseService;

    /**
     * @Inject()
     * @var StoreShopPrinterService
     */
    private $storeShopPrinterService;

    /**
     * @Inject()
     * @var StoreShopMessageService
     */
    private $storeShopMessageService;
    /**
     * @Inject()
     * @var StoreShopDeliverService
     */
    private $storeShopDeliverService;


    /**
     * 获取店铺列表
     * @RequestMapping(path="/v1/shop", methods="get")
     * @param RequestInterface $request
     *
     * @return array
     */
    public function index(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = isset($params['perpage']) ? (int)($params['perpage']) : 5000;
        $field = [
            'shop_id', 'shop_name', 'province', 'city', 'country', 'address', 'create_at', 'shop_desc', 'status', 'shop_group_id'
        ];
        $shopType = $params['shop_type'] ?? null;
        if (!empty($params['activityId'])) {
            //活动相关店铺列表
            $list = $this->storeShopService->getModelShops($params['activityId'], $params['type'], (int)$perPage, 'activity');
        } elseif (!empty($params['navigationId'])) {
            //首页管理相关店铺列表（图文导航、轮播、弹窗等等）
            $list = $this->storeShopService->getModelShops($params['navigationId'], $params['type'], (int)$perPage, 'navigation', $shopType);
        } else {
            //店铺列表
            $list = $this->storeShopService->getList($params, (int)$perPage, $field);
        }
        if (!$list['code']) {
            return $this->success($list['data']->items(), '获取成功', $list['data']->total());
        } else {
            return $this->failed($list['code']);
        }
    }

    /**
     * 获取店铺信息
     * @RequestMapping(path="/v1/shop/{id:\d+}", methods="get")
     * @param int $id
     *
     * @return array
     */
    public function info(int $id)
    {
        $res = $this->storeShopService->getInfoById((int)$id);
        if (!$res['code']) {
            return $this->success($res['data'], '获取成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 添加门店
     * @PostMapping(path="/v1/shop", methods="post")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param ShopRequest $request
     *
     * @return array
     */
    public function store(ShopRequest $request)
    {
        $params = $request->validated();
        $res = $this->storeShopService->add($params);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }

    /**
     * 编辑门店
     * @PutMapping(path="/v1/shop/{id:\d+}", methods="put")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id
     * @param ShopRequest $request
     *
     * @return array
     */
    public function update(int $id, ShopRequest $request)
    {
        $params = $request->validated();
        $params['shop_id'] = $id;
        $res = $this->storeShopService->update($params);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 店铺营业/关店/歇业
     * @PutMapping(path="/v1/shop/{id:\d+}/status", methods="put")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id
     *
     * @return array
     */
    public function editStatus(int $id, RequestInterface $request)
    {
        $type = $request -> input('type') ?? '';
        $res = $this->storeShopService->editStatus('shop', $id, $type);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 店铺绑定店群
     * @PostMapping(path="/v1/shop/bind/group", methods="post")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     *
     * @return array
     */
    public function bindGroup(RequestInterface $request)
    {
        $shop_id = $request->input('shop_id');
        $shop_group_id = $request->input('shop_group_id');
        if (!$shop_id) return $this->failed(ErrorCode::SYSTEM_INVALID);
        if (!$shop_group_id) return $this->failed(ErrorCode::SYSTEM_INVALID);
        $res = $this->storeShopService->shopBindGroup((int)$shop_id, (int)$shop_group_id);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 店铺解除绑定店群
     * @PostMapping(path="/v1/shop/unbind/group", methods="post")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     *
     * @return array
     */
    public function unBindGroup(RequestInterface $request)
    {
        $shop_id = $request->input('shop_id');
        if (!$shop_id) return $this->failed(ErrorCode::SYSTEM_INVALID);
        $res = $this->storeShopService->shopUnBindGroup((int)$shop_id);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 商品部分店铺下架
     * @PostMapping(path="/v1/shop/unbind/goods", methods="post")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     *
     * @return array
     */
    public function unBindGoods(RequestInterface $request)
    {
        $goodsId = $request->input('goodsId');
        if (!$goodsId) return $this->failed(ErrorCode::SYSTEM_INVALID);
        $shopIds = $request->input('shopIds') ?? '';
        $shopType = $request->input('shopType') ?? 0;  // 商品类别：0为及时达，1为次日达
        $res = $this->resourceService->unBindGoods((int)$goodsId, $shopIds, $shopType);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 小程序附近店铺、团长列表
     * @RequestMapping(path="/v1/api/getNearShop", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function getNearShop(RequestInterface $request)
    {
        $longitude = $request->input('longitude');  //经度
        $latitude = $request->input('latitude');  //纬度
        if (!$longitude || !$latitude) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $activityID = $request->input('activityId') ?? null;    // 是否为团购活动的附近店铺
        $isNextDay = $request->input('isNextDay') ?? null;     // 是否为次日达
        $field = ['shop_id', 'latitude', 'longitude'];
        if ($activityID && !$isNextDay) {
            // 当前团购活动所有店铺列表，目前团购活动只和店铺绑定，没有团长
            $isRedisExist = $this -> baseService -> isRedisExist('resourceRedis', 'nearShop-actId:' . $activityID);
            if($isRedisExist){
                $res = $this->storeShopService->getShopDistance([], (float)$longitude, (float)$latitude, $activityID, null);
            }else{
                $shopId = $this->storeShopService->getShopIdsByActivityId($activityID);
                $shopIdArr = explode(',', $shopId);
                $list = $this->storeShopService->getShopInfobyShopIds($shopIdArr, $field)->toArray();
                $res = $this->storeShopService->getShopDistance($list, (float)$longitude, (float)$latitude, $activityID, null);
            }
        } elseif ($isNextDay && !$activityID) {
            // 次日达店铺列表定位，需要加入团长元素
            $isRedisExist = $this -> baseService -> isRedisExist('resourceRedis', 'nearShop-crd');
            if($isRedisExist){
                $res = $this->storeShopService->getShopDistance([], (float)$longitude, (float)$latitude, null, $isNextDay);
            }else{
                $shoplistArray = $this->storeShopService->getList(['mini' => 1], 5000, $field);
                if($shoplistArray['code']){
                    return $this->failed($shoplistArray['code']);
                }
                $teamLeaderList = $this->teamLeaderService->getList(['status'=>3], 5000, ['id', 'latitude', 'longitude']);
                if($teamLeaderList['code']){
                    return $this->failed($teamLeaderList['code']);
                }
                $teamLeaderListArray = $teamLeaderList['data']->toArray()['data'];
                // 把店铺列表和团长列表的 ID 统一为 shop_id 字段
                foreach ($teamLeaderListArray as $key => $val) {
                    $teamLeaderListArray[$key]['shop_id'] = $val['id'];  // 为了后面存入 Redis，将团长 id 键名改为 shop_id
                }
                $list = array_merge($shoplistArray['data']->items(), $teamLeaderListArray);
                $res = $this->storeShopService->getShopDistance($list, (float)$longitude, (float)$latitude, null, $isNextDay);
            }
        } elseif (!$activityID && !$isNextDay) {
            // 小程序首页及时达附近店铺，只有店铺元素
            $isRedisExist = $this -> baseService -> isRedisExist('resourceRedis', 'nearShop-jsd');
            if($isRedisExist){
                $res = $this->storeShopService->getShopDistance([], (float)$longitude, (float)$latitude);
            }else{
                $list = $this->storeShopService->getList(['mini' => 1], 5000, $field);
                if($list['code']){
                    return $this->failed($list['code']);
                }
                $res = $this->storeShopService->getShopDistance($list['data']->items(), (float)$longitude, (float)$latitude);
            }
        } else {
            return $this->failed(ErrorCode::NOT_HAVE_NEAR_SHOP);
        }

        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }

    }

    /**
     * 判断一点是否在指定区域（围栏算法）
     * @RequestMapping(path="/v1/api/checkPointInArea", methods="get")
     * @param RequestInterface $request
     *
     * @return array
     */
    public function checkPointInArea(RequestInterface $request)
    {
        $lng = $request->input('lng'); // 经度 x
        $lat = $request->input('lat'); // 纬度 y
        $shop_id = $request->input('shop_id'); // 根据店铺编号查出店铺
        if (!$lat || !$lng || !$shop_id) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res = $this->storeShopService->checkPointInArea($lng, $lat, $shop_id);
        if (!$res['code']) {
            return $this->success($res, '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     *@RequestMapping(path="/v1/api/shop", methods="get")
     * @return array
     */
    public function queryShop(){
        $params = $this->request->all();
        if (empty($params['keywords'])){
            return $this->failed(ErrorCode::SYSTEM_INVALID, "请输入关键字");
        }
        $where = ['address' => $params['keywords']];
        $field = ['shop_id','address','longitude','latitude'];
        $res = $this->storeShopService->queryShopList($where, $field);
        return $this->success($res, '获取列表成功', $res->count());
    }

    /**
     * App分享
     * @PostMapping(path="/v1/app/share", methods="post")
     * @param RequestInterface $request
     * @return array
     */
    public function appStoreShare(RequestInterface $request)
    {
        $shop_id = $request->getAttribute('shop_id');
        if (!$shop_id) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res = $this->shareService->dataShare($shop_id);
        if ($res) {
            return $this->success($res, '获取成功');
        } else {
            return $this->failed(ErrorCode::NOT_IN_FORCE);
        }
    }

    /**
     * App分享列表
     * @RequestMapping(path="/v1/app/share_list", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function appGoodsList(RequestInterface $request)
    {
        $shop_id = $request->getAttribute('shop_id');
        if (!$shop_id) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res = $this->shareService->dataShareList($shop_id);
        if ($res) {
            return $this->success($res, '获取成功');
        } else {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
    }

    /**
     * Api分享门店页面列表
     * @RequestMapping(path="/v1/api/share", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function share(RequestInterface $request)
    {
        $params = $request->all();
        $mid = $request->getAttribute('mid');
        $id = (int)$params['id'];
        if (!$id || !$mid) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res = $this->shareService->apiShare($mid, $id);
        if ($res) {
            return $this->success($res['data'], '获取成功');
        } else {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
    }

    /**
     * 次日达分享标题和图片
     * @RequestMapping(path="/v1/api/tomorrow_share", methods="get")
     * @return array
     */
    public function tomorrowShare()
    {
        $res = $this->shareService->shareConfig();
        if ($res) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed(ErrorCode::NOT_IN_FORCE);
        }
    }

    /**
     * 门店运营 当日营收
     * @RequestMapping(path="/v1/app/shop/income", methods="get")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function storeOperations(RequestInterface $request)
    {
        $shopId =$request->getAttribute('shop_id');
        if(empty($shopId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $where = ['shop_id'=>$shopId,'is_pay'=>Stakeholder::ORDER_PAID];
        $sumIncome = $this->storeShopService->storesIncome($where);
        $storeData = [
            'shop_id' => $shopId,
            'sum_income' => $sumIncome
        ];
        return $this->success($storeData);
    }
    /**
     * 商品分类
     * @RequestMapping(path="/v1/app/shop/goods_cate", methods="get") //要废弃
     * @return array
     * @author lulongfei
     */
    public function getGoodsHomeCate() ///要废弃
    {
        $where =   [
            'is_deleted'=>0,
            'status'=>1
        ];
        $field = [
            'id',
            'title'
        ];
        $goodsCateList = $this->categoryService->getCategoryList($where,$field);
        return $this->success($goodsCateList);
    }

    /**
     * 根据分类获取商品列表 全部|售卖中  is_all 1全部 包含门店上下架 平台上下架     2售卖中   包含门店上架  店铺上架（不分页）
     * @RequestMapping(path="/v1/app/shop/goods", methods="get")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function getGoodsListByCateId(RequestInterface $request)
    {
        $params = $request->all();
        $cateId = $params['cate_id'];
        $allGoods = $params['is_all'];
        $shopId =(int)$request->getAttribute('shop_id');
        if (empty($cateId) || empty($allGoods)||empty($shopId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $where = ['cate_id' =>$cateId, 'is_deleted'=>0, 'is_today'=> '1'];
        if($allGoods==2){
            $where['status']=1;
        }
        $goodsList =$this->storeShopService::getGoodsList($where,$shopId,$allGoods);
        return $this->success($goodsList);
    }
    /**
     * 根据分类获取商品列表 已下架  is_del 1 店铺下架 2平台下架   (分页)
     * @RequestMapping(path="/v1/app/shop/goods/sell_out", methods="get")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function soldOut(RequestInterface $request)
    {
        $params = $request->all();
        $shopId =(int)$request->getAttribute('shop_id');
        $isDelete = (int)$params['is_del'];
        if (empty($shopId) || empty($isDelete)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $perPage = $params['perpage']?? 10;
        $where = ['is_deleted'=>0,'is_today'=> '1'];
        if($isDelete==1){
            $flag = 1;
            $where['status']=1;
        }elseif ($isDelete==2){
            $flag = 2;
            $where['status']=0;
        }else{
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        $res =$this->storeShopService::getSellGoodsList($where,$shopId,$flag,$perPage);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data']['goodsList'], '获取成功', $res['data']['total']);
        }
    }
    /**
     * 搜索商品  平台上架
     * @RequestMapping(path="/v1/app/shop/goods/search", methods="post")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function getGoodsSearchByName(RequestInterface $request)
    {
        $params = $request->all();
        $shopId =(int)$request->getAttribute('shop_id');
        $goodsName = trim($params['goods_name']);
        if (empty($shopId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $where = ['is_deleted'=>0, 'status'=>1, 'is_today'=> '1'];
        if(empty($goodsName)){
            return $this->success([]);
        }
        $goodsList =$this->storeShopService::GoodsSearchName($where,$goodsName,$shopId);
        return $this->success($goodsList);
    }
    /**
     * 店铺商品上下架
     * @RequestMapping(path="/v1/app/shop/goods/status", methods="post")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function standUpAndDown(RequestInterface $request)
    {
        $params = $request->all();
        $shopId =(int)$request->getAttribute('shop_id');
        $goodsId = $params['goods_id'];
        if (empty($shopId) ||empty($goodsId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res =$this->storeShopService::setGoodsInfoById($goodsId,$shopId);
        if($res){
            return $this->success([], '成功');
        }else{
            return $this->failed(ErrorCode::NOT_IN_FORCE,'操作未生效，请刷新后重试!');
        }
    }

    /**
     * 店铺会员
     * @RequestMapping(path="/v1/app/shop/member", methods="get")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function memberManagement(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = !empty($params['perpage']) ? $params['perpage'] : 10;
        $field = [
            'face_url',
            'nickname',
            'phone',
            'status',
            'register_date',
        ];
        $memberList = $this->storeShopService->getShopMemberList($perPage,$field);
        return $this->success($memberList->items(),'获取成功',$memberList->total());
    }

    /**
     * 今日营收明细
     * @RequestMapping(path="/v1/app/shop/online_detail", methods="get")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function onLineDetail(RequestInterface $request)
    {
        $shopId =(int)$request->getAttribute('shop_id');
        if (empty($shopId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $detail =  $this->storeShopService->storesIncomeDetail(['shop_id'=>$shopId],'sum(total_price) as total_price,is_pay');
        $data = ['is_pay'=>0,'no_pay'=>0];
        foreach ($detail as $item){
            $item['is_pay']==Stakeholder::ORDER_PAID?   $data['is_pay']  = $item['total_price']: $data['no_pay']  = $item['total_price'];
        }
        return $this->success($data);
    }


    /**
     * 门店运营---财务对账--线上明细--已打款列表
     * @RequestMapping(path="/v1/app/shop/remit_list", methods="get")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function remitList(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = $params['perpage']?? 10;
        $page = $params['page'] ?? 1;
        $shopId =(int)$request->getAttribute('shop_id');
        if (empty($shopId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $startTime = $params['start_time']??date('Y-m-d',strtotime('-3 month'));
        $endTime = $params['end_time']??date('Y-m-d');
        $list = $this->storeShopService->getOrderSerialNumByShopId(['shop_id'=>$shopId,'is_pay'=>Stakeholder::ORDER_PAID],$startTime,$endTime,$page,$perPage);
        foreach ($list['data'] as $k=>$v){
            $list['data'][$k]['scope'] = $startTime."/".$endTime;
        }
        return $this->success($list['data'],'',$list['count']);
    }
    /**
     * 门店运营---财务对账--线下明细--已\未打款统计接口
     * @RequestMapping(path="/v1/app/shop/off_line_detail", methods="get")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function offLineDetail(RequestInterface $request)
    {
        $shopId =(int)$request->getAttribute('shop_id');
        if (empty($shopId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $detail =  $this->storeShopService->storesIncomeDetail(['shop_id'=>$shopId],'sum(real_price) as total_price,is_settlement',Stakeholder::FINANCE_CITIC);
        $data = ['is_settlement'=>0,'no_settlement'=>0];
        foreach ($detail as $item){
            $item['is_settlement']==1? $data['is_settlement']  = $item['total_price']: $data['no_settlement']  = $item['total_price'];
        }

        return $this->success($data);
    }

    /**
     * 门店运营---财务对账--线下明细--已打款列表
     * @RequestMapping(path="/v1/app/shop/off_lineremit_list", methods="get")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function offLineremitList(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = $params['perpage']?? 10;
        $page = $params['page'] ?? 1;
        $shopId =(int)$request->getAttribute('shop_id');
        if (empty($shopId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $startTime = $params['start_time']??date('Y-m-d',strtotime('-3 month'));
        $endTime = $params['end_time']??date('Y-m-d');
        $list = $this->storeShopService->getOrderSerialNumByShopId(['shop_id'=>$shopId,'is_settlement'=>1],$startTime,$endTime,$page,$perPage,Stakeholder::FINANCE_CITIC);
        foreach ($list['data'] as $k=>$v){
            $list['data'][$k]['scope'] = $startTime."/".$endTime;
        }
        return $this->success($list['data'],'',$list['count']);
    }

    /**
     * 门店运营---销售对账--日预计计收入接口
     * @RequestMapping(path="/v1/app/shop/sales_reconciliation", methods="get")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function salesReconciliation(RequestInterface $request)
    {
        $params = $request->all();
        $times = $params['times']??date('Y-m-d',time());
        $shopId =(int)$request->getAttribute('shop_id');
        if (empty($shopId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $data  = $this->storeShopService->shopRevenue($shopId,$times);
        return $this->success($data);
    }

    /**
     * 门店运营---销售对账--历史账单列表信息
     * @RequestMapping(path="/v1/app/shop/order_history", methods="get")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function orderHistory(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = $params['perpage']?? 10;
        $page = $params['page'] ?? 1;
        $shopId =(int)$request->getAttribute('shop_id');
        if (empty($shopId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $income = $this->storeShopService->storestoGroupTimeIncome(['shop_id' => $shopId, 'is_pay' => 1], $page,$perPage);
        return $this->success($income['data'],'',$income['count']);
    }

    /**
     * 门店运营---销售对账--历史账单---当日订单明细
     * @RequestMapping(path="/v1/app/shop/today_order_detail", methods="get")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function todayOrderDetail(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = $params['perpage']?? 10;
        $shopId =(int)$request->getAttribute('shop_id');
        $times =  $params['times'];
        if (empty($shopId)||empty($times)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $income = $this->storeShopService->storestIncomeByTime(['shop_id'=>$shopId,'is_pay' => 1],$times,$perPage,"order_no,status,deal_type,freight_price,pay_type,total_price,coupon_cut,coupon_freight_cut");
        return $this->success($income['data'],'',$income['count']);
    }

    /**
     * 营业时间
     * @RequestMapping(path="/v1/app/shop/business_hours", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function businessHours(RequestInterface $request)
    {
        $shop_id =(int)$request->getAttribute('shop_id');
        $field = ['shop_id', 'start_time', 'end_time', 'status'];
        $res = $this->storeShopService->getInfoByShopId($shop_id, $field);
        if ($res) {
            return $this->success($res, '成功');
        } else {
            return $this->failed(ErrorCode::NOT_IN_FORCE);
        }
    }

    /**
     * 营业状态 开始营业或停止营业
     * @PutMapping(path="/v1/app/shop/business_status", methods="put")
     * @param RequestInterface $request
     * @return array
     */
    public function startAndEndTime(RequestInterface $request)
    {
        $params = $request->all();
        $shop_id =(int)$request->getAttribute('shop_id');
        $status_type = (int)$params['status'];
        if (empty($status_type) || empty($shop_id)){
            return $this->failed(ErrorCode::MISSING_PARAMETER);
        }
        if ($status_type == 1) {
            // 开始营业
            $status = 1;
        } elseif ($status_type == 2) {
            // 停止营业
            $status = 0;
        } else {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        $this->storeShopService->setShopInfoByShopId($shop_id, ['status' => $status]);
        return $this->success('', '成功');

    }

    /**
     * 设置营业时间段
     * @PostMapping(path="/v1/app/shop/setup_business_hours", methods="post")
     * @param RequestInterface $request
     * @return array
     */
    public function setUpBusinessHours(RequestInterface $request)
    {
        $params = $request->all();
        $shop_id =(int)$request->getAttribute('shop_id');
        $start_time = $params['start_time'];
        $end_time =  $params['end_time'];
        if (empty($start_time) || empty($end_time)) {
            return $this->failed(ErrorCode::MISSING_PARAMETER);
        }
        $set_time = ['start_time' => $start_time,'end_time' => $end_time];
        $res = $this->storeShopService->setShopInfoByShopId($shop_id, $set_time);
        if ($res) {
            return $this->success($set_time, '成功');
        } else {
            return $this->failed(ErrorCode::NOT_IN_FORCE);
        }
    }

    /**
     * 打印机设置添加
     * @PostMapping(path="/v1/app/shop/printer_setup", methods="post")
     * @param RequestInterface $request
     * @return array
     */
    public function printerSetup(RequestInterface $request)
    {
        $params = $request->all();
        if(empty($request->getAttribute('shop_id')) || empty($params['printer_name']) || empty($params['printer_terminal_number']) || empty($params['printer_password']))
        {
            return $this->failed(ErrorCode::MISSING_PARAMETER);
        }
        $data['shop_id'] = (int)$request->getAttribute('shop_id');
        $data['printer_password'] = password_hash($params['printer_password'],PASSWORD_DEFAULT);
        $data['printer_name'] = $params['printer_name'];
        $data['printer_terminal_number'] = $params['printer_terminal_number'];
        $res =$this->storeShopPrinterService->printerSettings($data);
        return $this->success($res, '成功');
    }

    /**
     * 打印机页面
     * @RequestMapping(path="/v1/app/shop/printer_page", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function printerPage(RequestInterface $request)
    {
        $shop_id =(int)$request->getAttribute('shop_id');
        $field = ['printer_name','printer_terminal_number','printer_password'];
        $return_data = $this->storeShopPrinterService->getPrinterInfoByPrinterId($shop_id,$field);
        return $this->success($return_data, '成功');
    }

    /**
     * 意见反馈
     * @PostMapping(path="/v1/app/shop/suggestion_feedback", methods="post")
     * @param RequestInterface $request
     * @return array
     */
    public function suggestionFeedback(RequestInterface $request)
    {
        $params = $request->all();
        if(empty($request->getAttribute('shop_id')) || empty($params['feedback_type']) || empty($params['feedback_content']) || empty($params['feedback_phone'])){
            return $this->failed(ErrorCode::MISSING_PARAMETER);
        }
        $data['shop_id']=$request->getAttribute('shop_id');
        $data['feedback_type']=$params['feedback_type'];
        $data['feedback_content']=$params['feedback_content'];
        $data['feedback_phone']=$params['feedback_phone'];
        $return_data = $this->storeShopMessageService->getMessage($data['shop_id'],$data);
        if($return_data){
            return $this->success('', '成功');
        } else{
            return $this->failed(ErrorCode::NOT_IN_FORCE);
        }
    }

    /**
     * 门店设置
     * @PostMapping(path="/v1/app/shop/store_settings", methods="post")
     * @param RequestInterface $request
     * @return array
     */
    public function storeSettings(RequestInterface $request)
    {
        $params = $request->all();
        // 参数验证
        if(empty($request->getAttribute('shop_id'))||empty($params['shop_name'])||empty($params['shop_man'])||empty($params['shop_tel'])||empty($params['low_price'])||
            empty($params['range'])||empty($params['delivery_money'])||empty($params['shop_desc'])||
            empty($params['address'])||empty($params['longitude'])||empty($params['latitude']))
        {
            return $this->failed(ErrorCode::MISSING_PARAMETER);
        }
        $params['shop_id'] = $request->getAttribute('shop_id');
        $shop_info = $this->storeShopService->getInfoByShopId($request->getAttribute('shop_id'),'shop_name');
        if(empty($shop_info['shop_name'])){
            $shop_id['shop_id'] = $this->storeShopService->shopInsertData($params);
            if(isset($shop_id['shop_id'])){
                $fields =[
                    'shop_id' => $shop_id['shop_id'],
                    'deliver_money' => $params['low_price'],
                    'shop_freight' => $params['delivery_money'],
                    'deliver_kilometre' => $params['range'],
                    'create_at' => date('Y-m-d H:i:s')
                ];
                $this->storeShopDeliverService->shopInsert($fields);
            }
        }else{
            $data = $this->storeShopService->setShopInfoByShopId($params['shop_id'],$params);
            $updateArr = [
                'deliver_money' => $params['low_price'],
                'shop_freight' => $params['delivery_money'],
                'deliver_kilometre' => $params['range']
            ];
            $this->storeShopDeliverService->shopUpdate($params['shop_id'],$updateArr);
            if(!$data){
                return $this->failed(ErrorCode::NOT_CONTENT_CHANGE);
            }
            $shop_id['shop_id'] = $params['shop_id'];
        }
        return $this->success($shop_id, '成功');
    }

    /**
     * 获取门店设置页面信息
     * @RequestMapping(path="/v1/app/shop/store_settings_page", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function storeSettingsPage(RequestInterface $request)
    {
        $shop_id =(int)$request->getAttribute('shop_id');
        $field = ['shop_id', 'shop_name', 'shop_man', 'shop_tel','is_must','start_time','end_time','shop_desc','address','latitude','longitude'];
        $shop = $this->storeShopService->getInfoByShopId($shop_id,$field);
        //获取店铺配送信息
        $data = ['deliver_money','shop_freight','deliver_kilometre'];
        $deliverArr = $this->storeShopDeliverService->getDeliverInfoByShopId($shop_id,$data);
        $shop_info =  array_merge($shop,$deliverArr);
        return $this->success($shop_info, '成功');
    }

    /**
     * 商家交易统计
     *
     * @RequestMapping(path="/v1/app/shop/{id:\d+}/statistics", methods="get")
     *
     * @return array
     */
    public function shopStatistics()
    {
        $id = $this->request->getAttribute('shop_id');
        // 佣金：会员在小程序次日达选择团长自提点所产生的订单，并且由团长进行全部商品核销完成后，成功等待订单退款周期结束后所奖励给团长的订单佣金。

        // 团长总数量
        $leader_count = $this->storeShopService->getLeaderCount($id);

        // 所有团长实时交易情况
        $today = $this->storeShopService->getDateShopWriteTrading(date('Y-m-d'), $id);
        $yesterday = $this->storeShopService->getDateShopWriteTrading(date('Y-m-d', strtotime('-1 day')), $id);
        $trading = [
            'today' => [
                'order_number'     => $today['number'],
                'order_commission' => $today['commission'],
                'total_price'      => $today['amount'],
            ],
            'yesterday' => [
                'leader_count'     => $this->storeShopService->getLeaderCount($id, date('Y-m-d', strtotime('-1 day'))),
                'order_number'     => $yesterday['number'],
                'order_commission' => $yesterday['commission'],
                'total_price'      => $yesterday['amount'],
            ]
        ];

        // 所有团长走势图
        $trend_chart = [];
        foreach ($this->teamLeaderService->salesOrderTrend($id)['data'] as $v) {
            $trend_chart[] = [
                'date'             => date('m.d', strtotime($v['date'])),
                'order_number'     => $v['sale_order'],
                'total_price'      => $v['total_price'],
            ];
        }

        // 销售额类别占比
        $percentage = $this->storeShopService->percentage($id);

        // 销售商品TOP 20
        $top20 = $this->storeShopService->top20($id);

        return $this->success(compact('leader_count', 'trading', 'trend_chart', 'percentage', 'top20'), '获取商家交易统计成功');
    }

    /**
     * 商家的团长列表
     *
     * @RequestMapping(path="/v1/app/shop/{id:\d+}/teamleader", methods="get")
     *
     * @param int $id
     * @return array
     */
    public function shopTeamLeaderList(int $id)
    {
        $row = $this->request->input('row', 15);
        $content = $this->request->input('content');
        if ($content) {
            $where = function ($q) use ($content) {
                $q->where('name', 'like', "%$content%")->orWhere('phone', 'like', "%$content%");
            };
        }
        $ret = $this->storeShopService->teamLeaderList($id, intval($row), $where ?? []);
        return $this->success($ret, '获取商家的团长列表成功');
    }

    /**
     * 团长交易详情
     *
     * @RequestMapping(path="/v1/app/shop/{id:\d+}/teamleader/{tid:\d+}/statistics", methods="get")
     *
     * @param int $id
     * @param int $tid
     * @return array
     */
    public function teamLeaderStatistics(int $id,int $tid)
    {
        // 团长个人详情
        $leader = $this->teamLeaderService->getInfoById($tid, [
            'id',
            'mid',
            'name',
            'status',
            'delivery_address',
            'detail_address',
            'phone',
            'opening_time',
            'closing_time',
            'updated_at',
            'last_business_hours',
            'add_up_commission',
        ]);
        if ($leader['code']) {
            return $this->failed($leader['code'], '不存在的团长');
        }

        $last_business_hours = $leader['data']['last_business_hours'] ?: strtotime($leader['data']['updated_at']);

        // 团长基础信息
        $base_info = [
            'name'                => $leader['data']['name'],
            'avatar'              => $leader['data']->member['face_url'] ?? '',
            'delivery_address'    => $leader['data']['delivery_address'],
            'detail_address'      => $leader['data']['detail_address'],
            'phone'               => $leader['data']['phone'],
            'status'              => $leader['data']['status'],
            'last_business_hours' => Carbon::parse($last_business_hours)->locale('zh')->diffForHumans(),
            'opening_time'        => $leader['data']['opening_time'],
            'closing_time'        => $leader['data']['closing_time'],
            'add_up_commission'   => $leader['data']['add_up_commission'],
        ];

        // 待分拣数量
        $wait_sort_number = $this->teamLeaderService->getQuantityToBeSorted($tid);

        // 待核销数量
        $wait_write_off_number = $this->storeShopService->getDataToBeWrittenOff($tid);

        // 团长实时交易情况
        $today = $this->storeShopService->getDateShopWriteTrading(date('Y-m-d'), $tid, 2);
        $yesterday = $this->storeShopService->getDateShopWriteTrading(date('Y-m-d', strtotime('-1 day')), $tid, 2);
        $trading = [
            'today' => [
                'order_number'     => $today['number'],
                'order_commission' => $today['commission'],
                'total_price'      => $today['amount'],
            ],
            'yesterday' => [
                'leader_count'     => $this->storeShopService->getLeaderCount($id, date('Y-m-d', strtotime('-1 day'))),
                'order_number'     => $yesterday['number'],
                'order_commission' => $yesterday['commission'],
                'total_price'      => $yesterday['amount'],
            ]
        ];

        // 走势图
        $trend_chart = [];
        foreach ($this->teamLeaderService->salesOrderTrend($id, $tid)['data'] as $v) {
            $trend_chart[] = [
                'date'         => date('m.d', strtotime($v['date'])),
                'order_number' => $v['sale_order'],
                'total_price'  => $v['total_price'],
            ];
        }

        return $this->success(compact('base_info', 'wait_sort_number', 'wait_write_off_number','trading', 'trend_chart'), '获取团长交易详情成功');
    }

    /**
     * 分拣列表
     * @RequestMapping(path="/v1/app/shop/sorting_list", methods="get")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function sortingList(RequestInterface $request)
    {
        $params = $request->all();
        if (!$params['shop_id']) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $perPage = !empty($params['perpage']) ? $params['perpage'] : 10;
        $page = !empty($params['page']) ? $params['page'] : 1;
        $leaderName = $params['leader_name']??'';
        $res =$this->teamLeaderService->sortingOrderList($params['shop_id'],$perPage,$page,$leaderName);
        if($res['code']){
            return $this->failed($res['code'],$res['msg']??'');
        }else{
            return $this->success($res['data'],'操作成功');
        }

    }
    /**
     *
     * 分拣详情
     * @RequestMapping(path="/v1/app/shop/sorting_detail", methods="get")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function sortingDetail(RequestInterface $request)
    {
        $params = $request->all();
        $shopId = $params['shop_id'];
        $leaderId = $params['leader_id'];
        $time = $params['time'];
        if (empty($leaderId)||empty($shopId)||empty($time)) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res = $this->teamLeaderService->sortingLeaderDetail($shopId,$leaderId,$time);
        if($res['code']){
            return $this->failed($res['code'],$res['msg']??'');
        }else{
            return $this->success($res['data'],'操作成功');
        }
    }

    /**
     * 分拣
     * @RequestMapping(path="/v1/app/shop/sorting", methods="post")
     * @param RequestInterface $request
     * @return array
     * @author lulongfei
     */
    public function sortingGoods(RequestInterface $request)
    {
        $params = $request->all();
        $shopId = $params['shop_id'];
        $leaderId = $params['leader_id'];
        $time = $params['time'];
        $goods = json_decode($params['goods'],true);
        if (empty($leaderId)||empty($shopId)||empty($time)||empty($goods)) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res  =$this->teamLeaderService->saveSortingLog($shopId,$leaderId,$time,$goods);
        if($res['code']){
            return $this->failed($res['code'],$res['msg']??'');
        }else{
            return $this->success($res['code'],'操作成功');
        }
    }

    /**
     * 次日达商品分类
     * @RequestMapping(path="/v1/app/shop/tomorrow_goods_cate", methods="get")
     * @return array
     */
    public function getTomorrowGoodsCategory()
    {
        $where =   [ 'is_deleted'=>0, 'status'=>1];
        $field = ['id', 'title'];
        $goodsCateList = $this->categoryService->getCategoryList($where,$field,1);
        return $this->success($goodsCateList);
    }

    /**
     * (次日达)根据分类获取商品列表 全部|售卖中  is_all 1全部 包含门店上下架 平台上下架     2售卖中   包含门店上架  店铺上架（不分页）
     * @RequestMapping(path="/v1/app/shop/tomorrow_goods", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function getTomorrowGoodsListByCateId(RequestInterface $request)
    {
        $params = $request->all();
        $cateId = $params['crd_cate_id'];
        $allGoods = $params['is_all'];
        $shopId =(int)$request->getAttribute('shop_id');
        if (empty($cateId) || empty($allGoods)||empty($shopId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $where = ['crd_cate_id' =>$cateId, 'is_deleted'=>0, 'is_next_day' => '1'];
        if($allGoods==2){
            $where['status']=1;
        }
        $goodsList =$this->storeShopService::getTomorrowGoodsList($where,$shopId,$allGoods);
        return $this->success($goodsList);
    }

    /**
     * (次日达)根据分类获取商品列表 已下架  is_del 1 店铺下架 2平台下架   (分页)
     * @RequestMapping(path="/v1/app/shop/goods/tomorrow_sell_out", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function tomorrowSoldOut(RequestInterface $request)
    {
        $params = $request->all();
        $shopId =(int)$request->getAttribute('shop_id');
        $isDelete = (int)$params['is_del'];
        if (empty($shopId) || empty($isDelete)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $perPage = $params['perpage']?? 10;
        $where = ['is_deleted'=>0, 'is_next_day' => '1'];
        if($isDelete==1){
            $flag = 1;
            $where['status']=1;
        }elseif ($isDelete==2){
            $flag = 2;
            $where['status']=0;
        }else{
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        $res =$this->storeShopService::getTomorrowSellGoodsList($where,$shopId,$flag,$perPage);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data']['goodsList'], '获取成功', $res['data']['total']);
        }
    }

    /**
     * (次日达)搜索商品  平台上架
     * @RequestMapping(path="/v1/app/shop/goods/tomorrow_search", methods="post")
     * @param RequestInterface $request
     * @return array
     */
    public function getTomorrowGoodsSearchByName(RequestInterface $request)
    {
        $params = $request->all();
        $shopId =(int)$request->getAttribute('shop_id');
        $goodsName = trim($params['goods_name']);
        if (empty($shopId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $where = ['is_deleted'=>0, 'status'=>1, 'is_next_day' => '1'];
        if(empty($goodsName)){
            return $this->success([]);
        }
        $goodsList =$this->storeShopService::tomorrowGoodsSearchName($where,$goodsName,$shopId);
        return $this->success($goodsList);
    }

    /**
     * (次日达)店铺商品上下架
     * @RequestMapping(path="/v1/app/shop/goods/tomorrow_status", methods="post")
     * @param RequestInterface $request
     * @return array
     */
    public function standTomorrowUpAndDown(RequestInterface $request)
    {
        $params = $request->all();
        $shopId =(int)$request->getAttribute('shop_id');
        $goodsId = $params['goods_id'];
        if (empty($shopId) || empty($goodsId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res =$this->storeShopService::setTomorrowGoodsInfoById($goodsId,$shopId);
        if($res){
            return $this->success([], '成功');
        }else{
            return $this->failed(ErrorCode::NOT_IN_FORCE,'操作未生效，请刷新后重试!');
        }
    }
}
